<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/_sys/tcms_admin_web_page_wed_ua.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_template_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpt_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_category_dbc.class.php');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_system_attribute_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpt_system_attribute_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_cache_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/admin_panel/classes/admin_user/admin_user_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/category/tcms_category_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/menu/item_types/tcms_menu_item_vpage_dbc.class.php');


class VPage_Manage_WP extends TCMS_Admin_Web_Page_WED_UA {
	public function create_view($name = 'default') {
		$ret = new TCMS_Admin_Page_View($this, $name, 'modules/tangra_cms/pages/_vpage/');

		return $ret;
	}


	protected function init_transit_vars() {
		$this->add_transit_var('category');
	}


	public function init() {
		parent::init();

		$v = $this->create_view();
		$this->add_view($v);

		$v2 = $this->create_view('not_exist');
		$this->add_view($v2);

		$manage_event = new Web_Event_Simple_Int('manage', Tangra_Parameter_Method::GET, 'manage');
		$this->wed->add_wed_event_action_pair($manage_event, 'manage_event', 20);


		$lock_event = new Web_Event_Simple_Int('lock', Tangra_Parameter_Method::GET, 'cache_lock');
		$lock_comp = new Web_Event_Composite('lock_comp');
		$lock_comp->add_web_event_simple($lock_event);
		$lock_comp->add_web_event_simple($manage_event);
		$this->wed->add_wed_event_action_pair($lock_comp, 'lock_event', 15);

		$cache_clear_event = new Web_Event_Simple_Int('cache_clear', Tangra_Parameter_Method::GET, 'cache_clear');
		$cache_clear_comp = new Web_Event_Composite('cache_clear_comp');
		$cache_clear_comp->add_web_event_simple($cache_clear_event);
		$cache_clear_comp->add_web_event_simple($manage_event);
		$this->wed->add_wed_event_action_pair($cache_clear_comp, 'cache_clear_event', 15);

		$unlink_event = new Web_Event_Simple_Int('unlink', Tangra_Parameter_Method::GET, 'unlink');
		$unlink_comp_event = new Web_Event_Composite('unlink_comp');
		$unlink_comp_event->add_web_event_simple($manage_event);
		$unlink_comp_event->add_web_event_simple($unlink_event);
		$this->wed->add_wed_event_action_pair($unlink_comp_event, 'unlink_event', 10);


		$link_event = new Web_Event_Simple_Int('link', Tangra_Parameter_Method::GET, 'link');
		$linkto_event = new Web_Event_Simple_Int('linkto', Tangra_Parameter_Method::GET, 'linkto');
		$link_comp_event = new Web_Event_Composite('link_comp');
		$link_comp_event->add_web_event_simple($manage_event);
		$link_comp_event->add_web_event_simple($link_event);
		$link_comp_event->add_web_event_simple($linkto_event);
		$this->wed->add_wed_event_action_pair($link_comp_event, 'link_event', 15);


		$online_event = new Web_Event_Simple_Int('online', Tangra_Parameter_Method::GET, 'online');
		$online_comp_event = new Web_Event_Composite('online_comp');
		$online_comp_event->add_web_event_simple($online_event);
		$online_comp_event->add_web_event_simple($manage_event);
		$this->wed->add_wed_event_action_pair($online_comp_event, 'online_event', 15);


		$this->prepare_preview_code();
	}


	protected function manage_event($vpage_id) {
		$dbc = $this->get_dbc();

		$vpage = new TCMS_VPage_DBC();

		if ($vpage->load_by_id($dbc, $vpage_id)) {
			$view = $this->_manage($vpage);
		} else {
			$view = $this->get_view('not_exist');
		}

		return $view;
	}


	private function _manage(TCMS_VPage_DBC $vpage) {
		$dbc = $this->get_dbc();

		$this->export('vpage', $vpage);

		$vp_template = new TCMS_VPage_Template_DBC();
		if ($vp_template->load_by_id($dbc, $vpage->get_template())) {
			$this->export('template_name', $vp_template->get_name());
			$this->export('template_hard_cache', $vp_template->get_hard_cache());

			$vpage_last_modified = $this->get_last_modified($vp_template, $vpage);
			// category pages may need update of last_modified
			if ($vpage_last_modified > $vpage->get_last_modified()) {
				try {
					$dbc->start_trans();
					TCMS_VPage_DBC::update_last_modified($dbc, $vpage->get_id(), false, $vpage_last_modified);
					$dbc->complete_trans();
				} catch (Exception $e) {
					$dbc->fail_trans();
					$dbc->complete_trans();
					throw $e;
				}
			}
			$this->export('vpage_last_modified', $vpage_last_modified);


			// Loading system attributes
			$t_sas = TCMS_VPT_System_Attribute_DBC::select_vpt_sas_for_template($dbc, $vpage->get_template());
			$page_system_attributes = TCMS_VPage_System_Attribute_DBC::load_all_for_vpage($dbc, $vpage->get_id());
			$missing_required_sa = false;
			foreach($t_sas as $key => &$tas) {
				if (array_key_exists($tas['id'], $page_system_attributes)) {
					$tas['vp_sa'] = $page_system_attributes[$tas['id']]->get_id();
					$tas['value'] = trim($page_system_attributes[$tas['id']]->get_value());
				} else {
					$tas['vp_sa'] = 0;
					$tas['value'] = '';
					if ($tas['required']) {
						$missing_required_sa = true;
					}
				}
			}

			$this->export('missing_required_sa', $missing_required_sa);
			$this->export('system_attributes', $t_sas);


			// loading content items
			$t_cis = TCMS_VPT_CI_DBC::load_vpt_cis_for_template($dbc, $vp_template->get_id());
			$vp_cis = TCMS_VPage_CI_DBC::load_cis_for_page($dbc, $vpage->get_id());
			$missing_required_ci = false;
			foreach($t_cis as $key => &$tis) {
				if (array_key_exists($tis['id'], $vp_cis)) {
					$tis['vp_ci'] = $vp_cis[$tis['id']]->get_id();
					$tis['vp_item_id'] = $vp_cis[$tis['id']]->get_ci_id();
				} else {
					$tis['vp_ci'] = 0;
					$tis['vp_item_id'] = 0;
					if ($tis['required']) {
						$missing_required_ci = true;
					}
				}
			}

			$this->export('missing_required_ci', $missing_required_ci);
			$this->export('cis', $t_cis);
		}

		// loading cache settings
		$settings_cache = new TCMS_Settings_Cache_DBC();
		if ($settings_cache->load_by_id($dbc, 1)) {
			$this->export('settings_cache', $settings_cache);
		} else {
			throw new Tangra_User_Exception('Cannot load settings cache');
		}


		// loading users for created by and last modified by
		$admin_user = new Admin_User_DBC();
		if ($admin_user->load_by_id($dbc, $vpage->get_created_by())) {
			$this->export('created_by', $admin_user->get_username());
		}
		if ($admin_user->load_by_id($dbc, $vpage->get_last_modified_by())) {
			$this->export('last_modified_by', $admin_user->get_username());
		}


		// loading categories that this page belongs to
		$categories = TCMS_VPage_Category_DBC::load_vpage_categories($dbc, $vpage->get_id());
		$this->export('categories', $categories);


		// loading menu items that are linked to this page (only of type TCMS_Menu_Item_VPage_DBC, "raw" links are not checked)
		$items_linking_to_vpage = TCMS_Menu_Item_VPage_DBC::load_items_linking_to_vpage($dbc, $vpage->get_id());
		$this->export('items_linking_to_vpage', $items_linking_to_vpage);
		$this->export('items_linking_to_vpage_count', count($items_linking_to_vpage));


		// loading current category (If any)
		$category_id = $this->get_transit_var('category', true);
		if ($category_id) {
			$category = new TCMS_Category_DBC();

			if (!$category->load_by_id($dbc, $category_id)) {
				throw new Tangra_Module_Exception('Cannot load TCMS_Category_DBC with id = '.$category_id);
			}

			$this->export('category', $category);
		}


		$cache_path = str_replace('/', '-', $vpage->get_path()).'-vp'.$vpage->get_id().'.html';
		$cache_file = $this->get__config()->get_scratch_dir().'tcms_cache/'.$cache_path;
		if(file_exists($cache_file)) {
			$this->export('cache_file', $cache_path);
			$this->export('cache_file_mtime', date('Y-m-d H:i:s', filemtime($cache_file)));
		}


		return $this->get_view('default');
	}


	protected function cache_clear_event($params) {
		$dbc = $this->get_dbc();

		$vpage = new TCMS_VPage_DBC();

		if ($vpage->load_by_id($dbc, $params['manage'])) {
			$cache_path = str_replace('/', '-', $vpage->get_path()).'-vp'.$vpage->get_id().'.html';
			$cache_file = $this->get__config()->get_scratch_dir().'tcms_cache/'.$cache_path;
			unlink($cache_file);

			$view = $this->create_redirect_view('admin/modules/tangra_cms/vpage/vpage_manage.php', array('manage' => $vpage->get_id()));
		} else {
			// if page not found, e.g some other admin delete it meanwhile - redirect to vpages list
			$view = $this->create_redirect_view('admin/modules/tangra_cms/vpage/vpages.php');
		}

		return $view;
	}


	protected function lock_event($params) {
		$dbc = $this->get_dbc();

		try {
			$dbc->start_trans();
			$vpage = new TCMS_VPage_DBC();

			if ($vpage->load_by_id($dbc, $params['manage'])) {
				$vpage->set_cache_locked($params['lock']);
				$vpage->save($dbc);
				$view = $this->create_redirect_view('admin/modules/tangra_cms/vpage/vpage_manage.php', array('manage' => $vpage->get_id()));
			} else {
				// if page not found, e.g some other admin delete it meanwhile - redirect to vpages list
				$view = $this->create_redirect_view('admin/modules/tangra_cms/vpage/vpages.php');
			}
			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}

		return $view;
	}


	protected function unlink_event($params) {
		$dbc = $this->get_dbc();
		try {
			$dbc->start_trans();
			TCMS_VPage_CI_DBC::delete($dbc, $params['unlink']);
			$current_user = $this->get_user();
			TCMS_VPage_DBC::update_last_modified($dbc, $params['manage'], $current_user->get_id());
			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}


		return $this->manage_event($params['manage']);
	}


	protected function link_event($params) {
		$vpt_ci_id = $params['linkto'];
		$ci_id = $params['link'];
		$vpage_id = $params['manage'];


		$vpt_ci = new TCMS_VPT_CI_DBC();
		$dbc = $this->get_dbc();
		if ($vpt_ci->load_by_id($dbc, $vpt_ci_id)) {
			if (TCMS_VPage_CI_DBC::is_unique_for_page($dbc, $vpage_id, $vpt_ci_id)) {
				$ci = new TCMS_VPage_CI_DBC();
				$ci->set_vpage($vpage_id);
				$ci->set_t_ci_id($vpt_ci_id);
				$ci->set_type($vpt_ci->get_ci_type());
				$ci->set_ci_id($ci_id);

				try {
					$dbc->start_trans();
					$ci->save($dbc);
					$current_user = $this->get_user();
					TCMS_VPage_DBC::update_last_modified($dbc, $vpage_id, $current_user->get_id());
					$dbc->complete_trans();
				} catch (Exception $e) {
					$dbc->fail_trans();
					$dbc->complete_trans();
					throw $e;
				}
			}
		}


		return $this->manage_event($vpage_id);
	}


	protected function online_event($params) {
		$online = $params['online'];
		$vpage_id = $params['manage'];

		$dbc = $this->get_dbc();

		$vpage = new TCMS_VPage_DBC();
		if ($vpage->load_by_id($dbc, $vpage_id)) {
			if ((boolean)$online != $vpage->get_online()) {
				$current_user = $this->get_user();
				try {
					$dbc->start_trans();
					TCMS_VPage_DBC::set_status_online($dbc, $vpage_id, $online, $current_user->get_id());
					$dbc->complete_trans();
				} catch (Exception $e) {
					$dbc->fail_trans();
					$dbc->complete_trans();
					throw $e;
				}
			}
		}

		return $this->manage_event($vpage_id);
	}


	protected function default_event() {
		throw new Tangra_User_Exception('Expecting manage parameter.');
	}


	private function find_username() {

	}


	private function can_go_online() {
		$dbc = $this->get_dbc();

		$t_sas = TCMS_VPT_System_Attribute_DBC::select_vpt_sas_for_template($dbc, $vpage->get_template());
		$page_system_attributes = TCMS_VPage_System_Attribute_DBC::load_all_for_vpage($dbc, $vpage_id);
		$missing_required_sa = false;
		foreach($t_sas as $key => &$tas) {
			if (!array_key_exists($tas['id'], $page_system_attributes)) {
				if ($tas['required']) {
					$missing_required_sa = true;
				}
			}
		}


		$t_cis = TCMS_VPT_CI_DBC::load_vpt_cis_for_template($dbc, $vp_template->get_id());
		$vp_cis = TCMS_VPage_CI_DBC::load_cis_for_page($dbc, $vpage_id);
		$missing_required_ci = false;
		foreach($t_cis as $key => &$tis) {
			if (!array_key_exists($tis['id'], $vp_cis)) {
				if ($tis['required']) {
					$missing_required_ci = true;
				}
			}
		}


		return !($missing_required_sa || $missing_required_ci);
	}


	private function prepare_preview_code() {
		$svm = $this->get_svm();
		if ($svm->is_global_var_registered('preview_code')) {
			$preview_code = $svm->get_global_var('preview_code');
		} else {
			$preview_code = md5(mt_rand());
			$svm->register_global_var('preview_code');
			$svm->set_global_var('preview_code', $preview_code);
		}

		$this->export('_tcms_preview_code', $preview_code);
	}


	/**
	 * Loads last_modified using template. Category pages' last_modified have to be same as latest last_modified of page in this category
	 *
	 * @param TCMS_VPage_Template_DBC $template
	 * @param TCMS_VPage_DBC $vpage
	 * @return unknown
	 */
	private function get_last_modified(TCMS_VPage_Template_DBC $template, TCMS_VPage_DBC $vpage) {
		$dbc = $this->get_dbc();

		require_once($this->get__config()->get_site_inc_dir().$template->get_wp_path());
		$page_class = $template->get_wp_class_name();
		$page = new $page_class($vpage, $template);
		$ret = $page->get_vpage_last_modified($dbc);

		return $ret;
	}
}